package com.taotao.manage.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.manage.utils.FastDFSClient;
import com.taotao.manage.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RequestMapping("/pic")
@RestController
public class PicUploadController {
    //允许上传的图片类型
    private static final String[] IMAGE_TYPES={".jpg",".png",".bmp",".jpeg",".gif"};
    @Value("${TAOTAO_IMAGE_PATH}")
    private String TAOTAO_IMAGE_PATH;

    //处理json字符串的工具类
    private static final ObjectMapper MAPPER = new ObjectMapper();
    /**
     * 将前端上传的图片接收并保存
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST,produces = MediaType.TEXT_HTML_VALUE)
    public String upload(@RequestParam(value = "uploadFile")MultipartFile multipartFile) throws Exception {
        PicUploadResult result = new PicUploadResult();
        result.setError(1);

        boolean isLegal=false;
        //1.校验图片后缀
        for (String imageType : IMAGE_TYPES) {
            if (multipartFile.getOriginalFilename().indexOf(imageType)>0){
                isLegal=true;
                break;
            }
        }
        if (isLegal){
            try {
                //校验图片内容
                BufferedImage image = ImageIO.read(multipartFile.getInputStream());
                result.setWidth(image.getWidth()+"");
                result.setHeight(image.getHeight()+"");
                //上传图片
                FastDFSClient fastDFSClient = new FastDFSClient("tracker.conf");
                String originalFilename = multipartFile.getOriginalFilename();
                String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                String url = fastDFSClient.uploadFile(multipartFile.getBytes(),ext);
                result.setUrl(TAOTAO_IMAGE_PATH+"/"+url);
                result.setError(0);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return MAPPER.writeValueAsString(result);
    }

}
